/**
 * UI管理模块
 * 处理所有UI更新和动画效果
 */

import { RESOURCE_TYPES, extractResourceValue } from './resources.js';

// UI元素缓存
let elements = {};

/**
 * 初始化UI元素引用
 * @param {Object} elementsRef 元素引用对象
 */
export function initUI(elementsRef) {
    elements = elementsRef;
}

/**
 * 更新资源显示
 * @param {HTMLElement} container 容器元素
 * @param {Object} resources 资源对象
 */
export function updateResourceDisplay(container, resources) {
    if (!container) return;
    
    // 清空现有内容
    container.innerHTML = '';
    
    // 为每种资源创建显示元素
    for (const resourceId in resources) {
        if (resources[resourceId] > 0) {
            const resourceType = Object.values(RESOURCE_TYPES).find(type => type.id === resourceId);
            if (!resourceType) continue;
            
            const resourceElement = document.createElement('div');
            resourceElement.className = 'resource-item';
            resourceElement.innerHTML = `
                <span class="resource-icon" style="color: ${resourceType.color}">${resourceType.icon}</span>
                <span class="resource-amount">${resources[resourceId]}</span>
                <span class="resource-name">${resourceType.name}</span>
            `;
            container.appendChild(resourceElement);
        }
    }
    
    // 如果没有资源，显示一个默认值
    if (container.children.length === 0) {
        container.innerHTML = '<div class="resource-item">无资源</div>';
    }
}

/**
 * 更新游戏UI显示
 * @param {Object} gameState 游戏状态
 */
export function updateUI(gameState) {
    // 兼容旧版UI
    if (elements.playerCoins) {
        elements.playerCoins.textContent = gameState.playerResources[RESOURCE_TYPES.GOLD.id] || 0;
    }
    if (elements.aiCoins) {
        elements.aiCoins.textContent = gameState.aiResources[RESOURCE_TYPES.GOLD.id] || 0;
    }
    
    // 更新新版资源显示
    if (elements.playerResourcesContainer) {
        updateResourceDisplay(elements.playerResourcesContainer, gameState.playerResources);
    }
    if (elements.aiResourcesContainer) {
        updateResourceDisplay(elements.aiResourcesContainer, gameState.aiResources);
    }
    
    // 更新资源池选择器
    if (elements.poolSelector) {
        elements.poolSelector.value = gameState.poolConfig.name;
    }
}

/**
 * 初始化资源滑块
 * @param {HTMLElement} slider 滑块元素
 * @param {HTMLElement} valueDisplay 值显示元素
 * @param {number} maxValue 最大值
 * @param {number} initialValue 初始值
 */
export function initResourceSlider(slider, valueDisplay, maxValue, initialValue = 0) {
    if (!slider) return;
    
    // 设置滑块范围和初始值
    slider.min = 0;
    slider.max = maxValue;
    slider.value = Math.min(initialValue, maxValue);
    
    // 更新显示值
    if (valueDisplay) {
        valueDisplay.textContent = slider.value;
    }
    
    // 添加事件监听
    slider.addEventListener('input', function() {
        if (valueDisplay) {
            valueDisplay.textContent = this.value;
        }
        
        // 添加滑块动画效果
        const value = parseInt(this.value);
        const max = parseInt(this.max);
        const percentage = (value / max) * 100;
        this.style.background = `linear-gradient(to right, #3498db ${percentage}%, #ddd ${percentage}%)`;
        
        // 更新投资预览
        if (typeof window.updateInvestmentPreview === 'function') {
            window.updateInvestmentPreview();
        }
    });
    
    // 初始化滑块背景
    const value = parseInt(slider.value);
    const max = parseInt(slider.max);
    const percentage = (value / max) * 100;
    slider.style.background = `linear-gradient(to right, #3498db ${percentage}%, #ddd ${percentage}%)`;
}

/**
 * 根据资源池配置更新UI
 * @param {Object} gameState 游戏状态
 */
export function updateUIForPoolConfig(gameState) {
    // 获取玩家资源
    const playerResources = gameState.playerResources;
    
    // 更新金币滑块
    initResourceSlider(
        elements.investmentSlider, 
        elements.investmentValue, 
        playerResources[RESOURCE_TYPES.GOLD.id] || 0, 
        Math.min(5, playerResources[RESOURCE_TYPES.GOLD.id] || 0)
    );
    
    // 更新信任值滑块和显示
    if (elements.trustInvestmentGroup && elements.trustInvestmentSlider) {
        const trustAmount = playerResources[RESOURCE_TYPES.TRUST.id] || 0;
        if (trustAmount > 0) {
            elements.trustInvestmentGroup.style.display = 'block';
            initResourceSlider(elements.trustInvestmentSlider, elements.trustInvestmentValue, trustAmount, 0);
        } else {
            elements.trustInvestmentGroup.style.display = 'none';
        }
    }
    
    // 更新风险点滑块和显示
    if (elements.riskInvestmentGroup && elements.riskInvestmentSlider) {
        const riskAmount = playerResources[RESOURCE_TYPES.RISK.id] || 0;
        if (riskAmount > 0) {
            elements.riskInvestmentGroup.style.display = 'block';
            initResourceSlider(elements.riskInvestmentSlider, elements.riskInvestmentValue, riskAmount, 0);
        } else {
            elements.riskInvestmentGroup.style.display = 'none';
        }
    }
    
    // 更新投资预览
    if (typeof window.updateInvestmentPreview === 'function') {
        window.updateInvestmentPreview();
    }
}

/**
 * 切换游戏阶段
 * @param {String} phase 目标阶段
 */
export function switchPhase(phase) {
    // 隐藏所有阶段
    if (elements.investmentPhase) elements.investmentPhase.classList.remove('active');
    if (elements.returnPhase) elements.returnPhase.classList.remove('active');
    if (elements.resultPhase) elements.resultPhase.classList.remove('active');
    if (elements.finalResultPhase) elements.finalResultPhase.classList.remove('active');
    if (elements.historyPhase) elements.historyPhase.classList.remove('active');
    
    // 显示目标阶段
    switch (phase) {
        case 'investment':
            if (elements.investmentPhase) elements.investmentPhase.classList.add('active');
            break;
        case 'return':
            if (elements.returnPhase) elements.returnPhase.classList.add('active');
            break;
        case 'result':
            if (elements.resultPhase) elements.resultPhase.classList.add('active');
            break;
        case 'finalResult':
            if (!elements.finalResultPhase) {
                elements.finalResultPhase = createFinalResultPhase();
                document.querySelector('.container').appendChild(elements.finalResultPhase);
            }
            elements.finalResultPhase.classList.add('active');
            
            // 更新最终结果显示
            if (elements.playerFinalCoins) {
                animateNumber(elements.playerFinalCoins, 0, gameState.playerResources[RESOURCE_TYPES.GOLD.id] || 0, 800);
            }
            if (elements.aiFinalCoins) {
                animateNumber(elements.aiFinalCoins, 0, gameState.aiResources[RESOURCE_TYPES.GOLD.id] || 0, 800);
            }
            
            // 更新最终结果
            if (elements.finalWinner) {
                // 计算总资源价值
                let playerValue = 0;
                let aiValue = 0;
                
                for (const resourceId in gameState.playerResources) {
                    const resourceType = Object.values(RESOURCE_TYPES).find(type => type.id === resourceId);
                    if (resourceType) {
                        playerValue += gameState.playerResources[resourceId] * resourceType.baseValue;
                    }
                }
                
                for (const resourceId in gameState.aiResources) {
                    const resourceType = Object.values(RESOURCE_TYPES).find(type => type.id === resourceId);
                    if (resourceType) {
                        aiValue += gameState.aiResources[resourceId] * resourceType.baseValue;
                    }
                }
                
                if (playerValue > aiValue) {
                    elements.finalWinner.textContent = "你赢了！";
                    elements.finalWinner.className = "win";
                } else if (aiValue > playerValue) {
                    elements.finalWinner.textContent = "AI赢了！";
                    elements.finalWinner.className = "lose";
                } else {
                    elements.finalWinner.textContent = "平局";
                    elements.finalWinner.className = "tie";
                }
            }
            break;
        case 'history':
            if (!elements.historyPhase) {
                elements.historyPhase = createHistoryPhase();
                document.querySelector('.container').appendChild(elements.historyPhase);
            }
            updateHistoryPhase();
            elements.historyPhase.classList.add('active');
            break;
    }
}

/**
 * 创建最终结果阶段
 * @returns {HTMLElement} 创建的DOM元素
 */
export function createFinalResultPhase() {
    const finalResultPhase = document.createElement('div');
    finalResultPhase.id = 'finalResultPhase';
    finalResultPhase.className = 'phase';
    finalResultPhase.innerHTML = `
        <h2>游戏结束</h2>
        <div class="final-result">
            <p>你的最终金币：<span id="playerFinalCoins">0</span> 枚</p>
            <p>AI的最终金币：<span id="aiFinalCoins">0</span> 枚</p>
            <p class="final-winner">结果：<span id="finalWinner">平局</span></p>
        </div>
        <div class="buttons">
            <button id="viewHistory">查看历史</button>
            <button id="restartGame">重新开始</button>
        </div>
    `;
    
    // 绑定事件
    finalResultPhase.querySelector('#viewHistory').addEventListener('click', () => {
        switchPhase('history');
    });
    
    finalResultPhase.querySelector('#restartGame').addEventListener('click', () => {
        if (typeof window.resetGame === 'function') {
            window.resetGame();
        }
    });
    
    // 添加元素引用
    elements.playerFinalCoins = finalResultPhase.querySelector('#playerFinalCoins');
    elements.aiFinalCoins = finalResultPhase.querySelector('#aiFinalCoins');
    elements.finalWinner = finalResultPhase.querySelector('#finalWinner');
    
    return finalResultPhase;
}

/**
 * 创建历史阶段
 * @returns {HTMLElement} 创建的DOM元素
 */
export function createHistoryPhase() {
    const historyPhase = document.createElement('div');
    historyPhase.id = 'historyPhase';
    historyPhase.className = 'phase';
    historyPhase.innerHTML = `
        <h2>游戏历史</h2>
        <div class="history-container">
            <table id="historyTable">
                <thead>
                <tr>
                    <th>回合</th>
                    <th>投资</th>
                    <th>增值</th>
                    <th>返还</th>
                    <th>你的收益</th>
                    <th>AI收益</th>
                    <th>AI策略</th>
                </tr>
                </thead>
                <tbody id="historyTableBody"></tbody>
            </table>
        </div>
        <div class="trust-chart">
            <h3>信任度变化图</h3>
            <div id="trustChartContainer"></div>
        </div>
        <div class="buttons">
            <button id="backToGame">返回游戏</button>
            <button id="viewFullHistory">查看完整历史</button>
        </div>
    `;
    
    // 绑定事件
    historyPhase.querySelector('#backToGame').addEventListener('click', () => {
        if (window.gameState.currentRound > window.gameState.maxRounds) {
            switchPhase('finalResult');
        } else {
            switchPhase('investment');
        }
    });
    
    historyPhase.querySelector('#viewFullHistory').addEventListener('click', () => {
        // 将当前会话历史编码到URL中传递给历史页面
        const sessionData = btoa(encodeURIComponent(JSON.stringify(window.gameState.history)));
        window.location.href = `history.html#session=${sessionData}`;
    });
    
    return historyPhase;
}

/**
 * 更新历史阶段显示
 */
export function updateHistoryPhase() {
    if (!elements.historyPhase) return;
    
    const historyTableBody = elements.historyPhase.querySelector('#historyTableBody');
    if (!historyTableBody) return;
    
    // 清空表格
    historyTableBody.innerHTML = '';
    
    // 填充历史记录
    window.gameState.history.forEach(record => {
        const tr = document.createElement('tr');
        
        // 获取投资金额
        const investmentValue = extractResourceValue(record.investment);
        
        // 获取增值金额
        const multipliedValue = extractResourceValue(record.multipliedAmount);
        
        // 获取返还金额
        const returnValue = extractResourceValue(record.returnAmount);
        
        // 获取玩家收益
        const playerGainValue = extractResourceValue(record.playerGain);
        
        // 获取AI收益
        const aiGainValue = extractResourceValue(record.aiGain);
        
        // 设置行样式
        if (parseFloat(record.returnRate) <= 0.15 && record.strategy === 'psychological') {
            tr.classList.add('deception-round');
            tr.title = '这一轮AI可能使用了欺骗策略';
        }
        
        tr.innerHTML = `
            <td>${record.round}</td>
            <td>${investmentValue}</td>
            <td>${multipliedValue}</td>
            <td>${returnValue}</td>
            <td class="${playerGainValue > 0 ? 'gain-positive' : playerGainValue < 0 ? 'gain-negative' : 'gain-zero'}">${playerGainValue > 0 ? '+' : ''}${playerGainValue}</td>
            <td class="${aiGainValue > 0 ? 'gain-positive' : aiGainValue < 0 ? 'gain-negative' : 'gain-zero'}">${aiGainValue > 0 ? '+' : ''}${aiGainValue}</td>
            <td>${getStrategyBadge(record.strategy)}</td>
        `;
        
        historyTableBody.appendChild(tr);
    });
    
    // 创建信任度图表
    createTrustChart();
}

/**
 * 获取策略徽章HTML
 * @param {String} strategy 策略ID
 * @returns {String} 徽章HTML
 */
function getStrategyBadge(strategy) {
    const strategyNames = {
        'good': '好人AI',
        'bad': '坏人AI',
        'fair': '公平AI',
        'psychological': '心理战AI',
        'vengeful': '报复性AI'
    };
    
    return `<span class="badge badge-${strategy}">${strategyNames[strategy] || strategy}</span>`;
}

/**
 * 创建信任度图表
 */
function createTrustChart() {
    const chartContainer = document.getElementById('trustChartContainer');
    if (!chartContainer) return;
    
    // 清空容器
    chartContainer.innerHTML = '';
    
    // 简单文本图表
    const history = window.gameState.history;
    if (history.length === 0) {
        chartContainer.textContent = '暂无历史数据';
        return;
    }
    
    // 创建简单的ASCII图表
    let chartHTML = '<pre class="text-chart">';
    chartHTML += '信任度: ';
    
    history.forEach((record, index) => {
        // 计算返还比例
        let returnRatio = 0;
        if (record.multipliedAmount > 0) {
            returnRatio = record.returnAmount / record.multipliedAmount;
        }
        
        // 根据返还比例显示不同符号
        if (returnRatio > 0.5) {
            chartHTML += '↑'; // 高返还
        } else if (returnRatio > 0.3) {
            chartHTML += '→'; // 中等返还
        } else {
            chartHTML += '↓'; // 低返还
        }
        
        // 添加分隔符
        if (index < history.length - 1) {
            chartHTML += '-';
        }
    });
    
    chartHTML += '</pre>';
    chartContainer.innerHTML = chartHTML;
}

/**
 * 数字动画效果
 * @param {HTMLElement} element 目标元素
 * @param {Number} start 起始值
 * @param {Number} end 结束值
 * @param {Number} duration 动画持续时间（毫秒）
 */
export function animateNumber(element, start, end, duration) {
    const startTime = performance.now();
    const updateNumber = (currentTime) => {
        const elapsedTime = currentTime - startTime;
        const progress = Math.min(elapsedTime / duration, 1);
        const currentValue = Math.floor(start + (end - start) * progress);
        
        element.textContent = currentValue;
        
        if (progress < 1) {
            requestAnimationFrame(updateNumber);
        } else {
            element.textContent = end;
        }
    };
    
    requestAnimationFrame(updateNumber);
}

/**
 * 更新返还阶段显示
 * @param {Object} gameState 游戏状态
 */
export function updateReturnPhase(gameState) {
    // 更新投资详情
    if (elements.investmentDetails) {
        updateResourceDisplay(elements.investmentDetails, gameState.investment);
    }
    
    // 更新增值详情
    if (elements.multipliedDetails) {
        updateResourceDisplay(elements.multipliedDetails, gameState.multipliedAmount);
    }
    
    // 更新返还详情
    if (elements.returnDetails) {
        updateResourceDisplay(elements.returnDetails, gameState.returnAmount);
    }
    
    // 更新倍率显示
    if (elements.multiplierDisplay) {
        const multiplier = gameState.history[gameState.history.length - 1].multiplier;
        elements.multiplierDisplay.textContent = `${multiplier.toFixed(1)}x`;
    }
    
    // 更新倍率详情
    if (elements.baseMultiplierDisplay) {
        elements.baseMultiplierDisplay.textContent = '3.0x';
    }
    
    // 更新信任值加成显示
    if (elements.trustBonusDisplay) {
        const trustBonus = gameState.history[gameState.history.length - 1].trustBonus;
        if (trustBonus > 0) {
            elements.trustBonusDisplay.style.display = 'block';
            elements.trustBonusDisplay.querySelector('span').textContent = `+${trustBonus.toFixed(1)}x`;
        } else {
            elements.trustBonusDisplay.style.display = 'none';
        }
    }
    
    // 更新风险修正显示
    if (elements.riskModifierDisplay) {
        const riskModifier = gameState.history[gameState.history.length - 1].riskModifier;
        if (riskModifier !== 0) {
            elements.riskModifierDisplay.style.display = 'block';
            const sign = riskModifier > 0 ? '+' : '';
            elements.riskModifierDisplay.querySelector('span').textContent = `${sign}${riskModifier.toFixed(1)}x`;
        } else {
            elements.riskModifierDisplay.style.display = 'none';
        }
    }
    
    // 更新返还率显示
    if (elements.returnRateDisplay) {
        const returnRate = gameState.history[gameState.history.length - 1].returnRate;
        elements.returnRateDisplay.textContent = `${Math.round(parseFloat(returnRate) * 100)}%`;
    }
    
    // 投资金额动画（兼容旧版UI）
    if (elements.investedAmount) {
        elements.investedAmount.textContent = "0";
        const goldInvestment = gameState.investment[RESOURCE_TYPES.GOLD.id] || 0;
        animateNumber(elements.investedAmount, 0, goldInvestment, 500);
    }
    
    // 延迟显示增值金额（兼容旧版UI）
    setTimeout(() => {
        if (elements.multipliedAmount) {
            elements.multipliedAmount.textContent = "0";
            const goldMultiplied = gameState.multipliedAmount[RESOURCE_TYPES.GOLD.id] || 0;
            animateNumber(elements.multipliedAmount, 0, goldMultiplied, 800);
        }
        
        // 再延迟显示返还金额（兼容旧版UI）
        setTimeout(() => {
            if (elements.returnAmount) {
                elements.returnAmount.textContent = "0";
                const goldReturn = gameState.returnAmount[RESOURCE_TYPES.GOLD.id] || 0;
                animateNumber(elements.returnAmount, 0, goldReturn, 1000);
            }
        }, 800);
    }, 600);
    
    // 为新版UI中的每个资源执行动画
    setTimeout(() => {
        // 投资动画
        if (elements.investmentDetails) {
            for (const resourceId in gameState.investment) {
                const element = document.getElementById(`${elements.investmentDetails.id}_${resourceId}`);
                if (element) {
                    animateNumber(element, 0, gameState.investment[resourceId], 500);
                }
            }
        }
        
        // 延迟显示增值动画
        setTimeout(() => {
            if (elements.multipliedDetails) {
                for (const resourceId in gameState.multipliedAmount) {
                    const element = document.getElementById(`${elements.multipliedDetails.id}_${resourceId}`);
                    if (element) {
                        animateNumber(element, 0, gameState.multipliedAmount[resourceId], 800);
                    }
                }
            }
            
            // 再延迟显示返还动画
            setTimeout(() => {
                if (elements.returnDetails) {
                    for (const resourceId in gameState.returnAmount) {
                        const element = document.getElementById(`${elements.returnDetails.id}_${resourceId}`);
                        if (element) {
                            animateNumber(element, 0, gameState.returnAmount[resourceId], 1000);
                        }
                    }
                }
            }, 800);
        }, 600);
    }, 100);
}

/**
 * 更新结果阶段显示
 * @param {Object} gameState 游戏状态
 */
export function updateResultPhase(gameState) {
    // 更新玩家资源显示
    if (elements.playerResultResources) {
        updateResourceDisplay(elements.playerResultResources, gameState.playerResources);
    }
    
    // 更新AI资源显示
    if (elements.aiResultResources) {
        updateResourceDisplay(elements.aiResultResources, gameState.aiResources);
    }
    
    // 使用动画效果显示金币数量（兼容旧版UI）
    if (elements.playerFinal) {
        animateNumber(elements.playerFinal, 0, gameState.playerResources[RESOURCE_TYPES.GOLD.id] || 0, 800);
    }
    if (elements.aiFinal) {
        animateNumber(elements.aiFinal, 0, gameState.aiResources[RESOURCE_TYPES.GOLD.id] || 0, 800);
    }
    
    // 为新版UI中的每个资源执行动画
    setTimeout(() => {
        // 玩家资源动画
        if (elements.playerResultResources) {
            for (const resourceId in gameState.playerResources) {
                const element = document.getElementById(`${elements.playerResultResources.id}_${resourceId}`);
                if (element) {
                    animateNumber(element, 0, gameState.playerResources[resourceId], 800);
                }
            }
        }
        
        // AI资源动画
        if (elements.aiResultResources) {
            for (const resourceId in gameState.aiResources) {
                const element = document.getElementById(`${elements.aiResultResources.id}_${resourceId}`);
                if (element) {
                    animateNumber(element, 0, gameState.aiResources[resourceId], 800);
                }
            }
        }
    }, 100);
    
    // 显示当前回合信息
    if (elements.currentRound) {
        elements.currentRound.textContent = gameState.currentRound;
        if (elements.totalRounds) {
            elements.totalRounds.textContent = gameState.maxRounds;
        }
    }
    
    // 添加倒计时提示
    if (elements.nextRoundInfo) {
        let countdown = 3;
        elements.nextRoundInfo.textContent = `下一回合将在 ${countdown} 秒后开始...`;
        
        const countdownInterval = setInterval(() => {
            countdown--;
            if (countdown > 0) {
                elements.nextRoundInfo.textContent = `下一回合将在 ${countdown} 秒后开始...`;
            } else {
                clearInterval(countdownInterval);
                elements.nextRoundInfo.textContent = "准备开始下一回合...";
            }
        }, 1000);
    }
    
    // 添加渐变背景色效果，根据玩家和AI的总资源价值差异
    const container = document.querySelector('.container');
    if (!container) return;
    
    // 计算总资源价值
    let playerValue = 0;
    let aiValue = 0;
    
    for (const resourceId in gameState.playerResources) {
        const resourceType = Object.values(RESOURCE_TYPES).find(type => type.id === resourceId);
        if (resourceType) {
            playerValue += gameState.playerResources[resourceId] * resourceType.baseValue;
        }
    }
    
    for (const resourceId in gameState.aiResources) {
        const resourceType = Object.values(RESOURCE_TYPES).find(type => type.id === resourceId);
        if (resourceType) {
            aiValue += gameState.aiResources[resourceId] * resourceType.baseValue;
        }
    }
    
    // 移除之前的背景色类
    container.classList.remove('player-winning', 'ai-winning', 'tie-game');
    
    // 根据资源价值差异添加新的背景色类
    if (playerValue > aiValue) {
        container.classList.add('player-winning');
    } else if (aiValue > playerValue) {
        container.classList.add('ai-winning');
    } else {
        container.classList.add('tie-game');
    }
}
